package com.dataex.dbtool;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: haoxw
 * @sine: 11-8-18 下午4:50
 */
public class PinyinUtils {

  // private static final Log log = LogFactory.getLog(PinyinUtils.class);
  private static final Logger log = LoggerFactory.getLogger(PinyinUtils.class);
  private static String defaultPropertyFile = "unicode_to_hanyu_pinyin.txt";
  public static Map<String, String> pinyinMap = new HashMap<String, String>();
  public static Map<String, String> shouzimuMap = new HashMap<String, String>();

  /** 初始化拼音的map */
  static {
    InputStream inputStream = PinyinUtils.class.getClassLoader().getResourceAsStream(
        defaultPropertyFile);
    // File file = new File(fileName);
    int count = 0;
    try {
      Reader fileReader = new InputStreamReader(inputStream);
      BufferedReader bufReader = new BufferedReader(fileReader);
      String line = null;
      while ((line = bufReader.readLine()) != null) {
        // log.info(line);
        String[] lines = line.split(" ");
        String value = "";
        if (lines.length >= 2) {
          value = lines[1];
          value = value.replace("(", "").replace(")", "");
          String[] res = value.split(",");
          if (null != res && res.length >= 1) {
            value = res[0].substring(0, res[0].length() - 1);
          }
        }
        pinyinMap.put(lines[0], value);
        if (value != null && value.length() > 1) {
          value = value.substring(0, 1);
        }
        shouzimuMap.put(lines[0], value);
        // log.info(lines[0] + " " + value);
        count++;

      }
      bufReader.close();
      fileReader.close();

    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
    log.info(count + "");
  }

  /**
   * 将字符串key包含的汉字转化成拼音，并且 leading and trailing white space removed 转换完毕全部为小写字母
   * isShouzimu为true时把汉语转化为拼音只取首字母 false时全部转换。 例子：isShouzimu=true abc中国:abczg
   * isShouzimu=false 中国def:zhongguodef
   * 
   * @param key
   * @return
   */
  public static String getPinyin(String key, boolean isShouzimu) {

    if (key == null) {
      return null;
    }
    StringBuffer strBuff = new StringBuffer();

    for (int i = 0; i < key.length(); i++) {
      char ch = key.charAt(i);
      if (ch < 256) {
        strBuff.append(ch);
        continue;
      }
      String ascii = Integer.toHexString(ch).toUpperCase();
      String value = null;
      if (!isShouzimu) {
        value = pinyinMap.get(ascii);
        strBuff.append(value);
      } else {
        value = shouzimuMap.get(ascii);
        strBuff.append(value);
      }
    }
    return strBuff.toString().trim();
  }

  /**
   * @param 传入Unicode编码的汉字结合
   * @return 对应的汉字的拼音组合，对于重复的汉字，在全拼后加对应的数字加一区别
   * 
   * */
  public static List<String> getPinyin(List<String> keys) {
    if (keys == null || keys.isEmpty()) {
      return null;
    }
    if (keys.size() > 5000) {
      throw new RuntimeException("每次转化的汉字组合最大为5000个，超过后请分批进行");
    }

    List<String> values = new ArrayList<String>(keys.size());
    HashMap<String, Integer> uniques = new HashMap<String, Integer>(keys.size());
    for (String key : keys) {
      String value = getPinyin(key, false);
      if (uniques.containsKey(value)) {
        int num = uniques.get(value) + 1;
        values.add(value + num);
        uniques.put(value, num);
        //预防类似 翟刘振，翟刘振，翟刘振1 这种情况的发生
        uniques.put(value + num, num);
      } else {
        uniques.put(value, 0);
        values.add(value);
      }
    }

    // make GC happen
    uniques.clear();
    uniques = null;

    return values;

  }
  
//  public static void main(String[] args) {
//    System.out.println(PinyinUtils.getPinyin("  abc中 国   ", false) + "******************");
//    ;
//
//    List<String> keys = new ArrayList<>();
//    keys.add("胡京红");
//    keys.add("胡静红");
//    keys.add("胡ji红");
//    keys.add("hu继红");
//    keys.add("hujihong");
//    keys.add("翟刘振");
//    keys.add("翟刘振");
//    keys.add("翟刘振");
//    keys.add("翟刘振1");
//    keys.add("翟刘振2");
//    keys.add("翟刘振3");
//    List<String> values = getPinyin(keys);
//    System.out.println(values);
//    
//    System.out.println(getPinyin("w我不知道不知道", true));
//    
//  }

}
